package com.ghh.algorithm;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author haihua.gu
 */

public class NumberDescription {
	private final String[]	UNITS		= { "", "万", "亿" };
	private final String[]	SUB_UNITS	= { "", "十", "百", "千" };
	private final String[]	NUMBERS		= { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };

	public String getDescription(long v) {
		String sValue = String.valueOf(v);
		while (sValue.length() % 4 != 0) {
			sValue = " " + sValue;
		}
		Pattern p = Pattern.compile(".{1,4}");
		Matcher m = p.matcher(sValue);
		List<String> lValue = new ArrayList<String>();
		while (m.find()) {
			lValue.add(m.group());
		}
		StringBuilder rs = new StringBuilder();
		for (int i = 0; i < lValue.size(); i++) {
			String unit = UNITS[(lValue.size() - 1) - i];
			String subValue = getSubDesc(lValue.get(i));
			rs.append(subValue + unit);
		}
		return rs.toString();
	}

	private String getSubDesc(String v) {
		StringBuilder rs = new StringBuilder();
		char preChar = ' ';
		for (int i = 0; i < v.length(); i++) {
			char c = v.charAt(i);
			if (c == ' ') {
				continue;
			}
			String subUnit = SUB_UNITS[v.length() - 1 - i];
			String value = NUMBERS[Integer.valueOf(String.valueOf(c))];
			if (c == '0') {
				if (preChar == '0') {
					continue;
				} else if (hasMoreNonZero(v, i + 1)) {
					rs.append(value);
				}
			} else {
				rs.append(value + subUnit);
			}

			preChar = c;
		}
		return rs.toString();
	}

	private boolean hasMoreNonZero(String v, int index) {
		for (int i = index; i < v.length(); i++) {
			if (v.charAt(index) != '0') {
				return true;
			}
		}
		return false;
	}

	public static void main(String[] args) {
		System.out.println(new NumberDescription().getDescription(450012300456l));
	}
}
